import subprocess
from IPy import IP
import re
while 1:
    try:
        need_ip = input("请输入需要检测的网段：")
        if re.search(r'\d{3}(\.(\d){1,3}){3}/[0-9]+', need_ip):
            pass
        else:
            raise ValueError
        ip = IP(need_ip)
        print("以下为未使用的ip：")
        for i in ip:
            # 有点误差，速度快
            temp = subprocess.getoutput(f"ping -n 1 -w 1 {i}")
            # 速度稍慢，准确高
            # a = subprocess.getoutput(f"ping -n 1 {i}")
            if "往返行程" in temp:
                with open('被使用ip.txt', 'a+', encoding='utf-8') as f:
                    f.write(f"{i}已被使用\n")
            else:
                print(i)
    except ValueError as e:
        print("请输入正确网段！")
    else:
        print("被使用ip已被写入  被使用ip.txt")
        break

